<template>
  <div class="app-container">
    <!-- 搜索栏 -->
    <el-card class="search-wrapper">
      <el-form :inline="true" :model="queryParams" class="demo-form-inline">
        <el-form-item>
          <el-input
            v-model="queryParams.keyword"
            placeholder="企业名称/营业执照号/税号"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item>
          <el-select v-model="queryParams.status" placeholder="状态" clearable>
            <el-option label="正常" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
          <el-button type="success" @click="handleAdd">新增企业</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-wrapper">
      <el-table
        v-loading="loading"
        :data="tableData"
        style="width: 100%"
        border
      >
        <el-table-column prop="org_id" label="ID" width="80" />
        <el-table-column prop="company_name" label="企业名称" min-width="200" show-overflow-tooltip />
        <el-table-column prop="business_license" label="营业执照号" min-width="150" show-overflow-tooltip />
        <el-table-column prop="legal_representative" label="法人代表" width="120" />
        <el-table-column prop="contact_name" label="联系人" width="120" />
        <el-table-column prop="contact_mobile" label="联系电话" width="130" />
        <el-table-column prop="black_card_no" label="关联黑卡" width="150" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status ? 'success' : 'danger'">
              {{ scope.row.status ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button
              type="primary"
              link
              @click="handleEdit(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              type="primary"
              link
              @click="handleDetail(scope.row)"
            >
              详情
            </el-button>
            <el-button
              :type="scope.row.status ? 'danger' : 'success'"
              link
              @click="handleStatus(scope.row)"
            >
              {{ scope.row.status ? '禁用' : '启用' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.page"
          v-model:page-size="queryParams.limit"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑弹窗 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="800px"
      append-to-body
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
      >
        <el-tabs v-model="activeTab">
          <el-tab-pane label="基本信息" name="basic">
            <el-form-item label="企业名称" prop="company_name">
              <el-input v-model="form.company_name" placeholder="请输入企业名称" />
            </el-form-item>
            <el-form-item label="营业执照号" prop="business_license">
              <el-input v-model="form.business_license" placeholder="请输入营业执照号" :disabled="dialogType === 'edit'" />
            </el-form-item>
            <el-form-item label="法人姓名" prop="legal_representative">
              <el-input v-model="form.legal_representative" placeholder="请输入法人姓名" />
            </el-form-item>
            <el-form-item label="企业地址" prop="company_address">
              <el-input v-model="form.company_address" placeholder="请输入企业地址" />
            </el-form-item>
          </el-tab-pane>
          
          <el-tab-pane label="联系方式" name="contact">
            <el-form-item label="联系电话" prop="contact_phone">
              <el-input v-model="form.contact_phone" placeholder="请输入联系电话" />
            </el-form-item>
            <el-form-item label="企业邮箱" prop="company_email">
              <el-input v-model="form.company_email" placeholder="请输入企业邮箱" />
            </el-form-item>
            <el-form-item label="联系人姓名" prop="contact_name">
              <el-input v-model="form.contact_name" placeholder="请输入联系人姓名" />
            </el-form-item>
            <el-form-item label="联系人电话" prop="contact_mobile">
              <el-input v-model="form.contact_mobile" placeholder="请输入联系人电话" />
            </el-form-item>
          </el-tab-pane>

          <el-tab-pane label="开票信息" name="invoice">
            <el-form-item label="开票类型" prop="invoice_type">
              <el-select v-model="form.invoice_type" placeholder="请选择开票类型">
                <el-option label="普通发票" value="normal" />
                <el-option label="专用发票" value="special" />
              </el-select>
            </el-form-item>
            <el-form-item label="纳税人识别号" prop="tax_number">
              <el-input v-model="form.tax_number" placeholder="请输入纳税人识别号" :disabled="dialogType === 'edit'" />
            </el-form-item>
            <el-form-item label="开户行" prop="bank_name">
              <el-input v-model="form.bank_name" placeholder="请输入开户行" />
            </el-form-item>
            <el-form-item label="银行账号" prop="bank_account">
              <el-input v-model="form.bank_account" placeholder="请输入银行账号" />
            </el-form-item>
            <el-form-item label="开票地址" prop="invoice_address">
              <el-input v-model="form.invoice_address" placeholder="请输入开票地址" />
            </el-form-item>
            <el-form-item label="开票电话" prop="invoice_phone">
              <el-input v-model="form.invoice_phone" placeholder="请输入开票电话" />
            </el-form-item>
          </el-tab-pane>

          <el-tab-pane label="黑卡信息" name="card">
            <el-form-item label="关联黑卡" prop="black_card_no">
              <el-input v-model="form.black_card_no" placeholder="请输入关联黑卡卡号" />
            </el-form-item>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 详情弹窗 -->
    <el-dialog
      title="企业详情"
      v-model="detailVisible"
      width="800px"
      append-to-body
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="企业名称">{{ detail.company_name }}</el-descriptions-item>
        <el-descriptions-item label="营业执照号">{{ detail.business_license }}</el-descriptions-item>
        <el-descriptions-item label="法人姓名">{{ detail.legal_representative }}</el-descriptions-item>
        <el-descriptions-item label="企业地址">{{ detail.company_address }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ detail.contact_phone }}</el-descriptions-item>
        <el-descriptions-item label="企业邮箱">{{ detail.company_email }}</el-descriptions-item>
        <el-descriptions-item label="联系人姓名">{{ detail.contact_name }}</el-descriptions-item>
        <el-descriptions-item label="联系人电话">{{ detail.contact_mobile }}</el-descriptions-item>
        <el-descriptions-item label="开票类型">{{ detail.invoice_type === 'normal' ? '普通发票' : '专用发票' }}</el-descriptions-item>
        <el-descriptions-item label="纳税人识别号">{{ detail.tax_number }}</el-descriptions-item>
        <el-descriptions-item label="开户行">{{ detail.bank_name }}</el-descriptions-item>
        <el-descriptions-item label="银行账号">{{ detail.bank_account }}</el-descriptions-item>
        <el-descriptions-item label="开票地址">{{ detail.invoice_address }}</el-descriptions-item>
        <el-descriptions-item label="开票电话">{{ detail.invoice_phone }}</el-descriptions-item>
        <el-descriptions-item label="关联黑卡">{{ detail.black_card_no }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="detail.status ? 'success' : 'danger'">
            {{ detail.status ? '正常' : '禁用' }}
          </el-tag>
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'

// 查询参数
const queryParams = reactive({
  page: 1,
  limit: 10,
  keyword: '',
  status: ''
})

// 表格数据
const loading = ref(false)
const tableData = ref([])
const total = ref(0)

// 弹窗相关
const dialogVisible = ref(false)
const dialogType = ref('add') // add or edit
const dialogTitle = ref('新增企业')
const activeTab = ref('basic')
const formRef = ref(null)
const form = reactive({
  company_name: '',
  business_license: '',
  legal_representative: '',
  company_address: '',
  contact_phone: '',
  company_email: '',
  invoice_type: 'normal',
  tax_number: '',
  bank_name: '',
  bank_account: '',
  invoice_address: '',
  invoice_phone: '',
  contact_name: '',
  contact_mobile: '',
  black_card_no: ''
})

// 详情弹窗
const detailVisible = ref(false)
const detail = ref({})

// 表单校验规则
const rules = {
  company_name: [
    { required: true, message: '请输入企业名称', trigger: 'blur' },
    { max: 200, message: '长度不能超过200个字符', trigger: 'blur' }
  ],
  business_license: [
    { required: true, message: '请输入营业执照号', trigger: 'blur' },
    { max: 50, message: '长度不能超过50个字符', trigger: 'blur' }
  ],
  legal_representative: [
    { required: true, message: '请输入法人姓名', trigger: 'blur' },
    { max: 50, message: '长度不能超过50个字符', trigger: 'blur' }
  ],
  company_address: [
    { required: true, message: '请输入企业地址', trigger: 'blur' },
    { max: 255, message: '长度不能超过255个字符', trigger: 'blur' }
  ],
  contact_phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  company_email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' },
    { max: 100, message: '长度不能超过100个字符', trigger: 'blur' }
  ],
  invoice_type: [
    { required: true, message: '请选择开票类型', trigger: 'change' }
  ],
  tax_number: [
    { required: true, message: '请输入纳税人识别号', trigger: 'blur' },
    { max: 50, message: '长度不能超过50个字符', trigger: 'blur' }
  ],
  bank_name: [
    { required: true, message: '请输入开户行', trigger: 'blur' },
    { max: 100, message: '长度不能超过100个字符', trigger: 'blur' }
  ],
  bank_account: [
    { required: true, message: '请输入银行账号', trigger: 'blur' },
    { max: 50, message: '长度不能超过50个字符', trigger: 'blur' }
  ],
  invoice_address: [
    { required: true, message: '请输入开票地址', trigger: 'blur' },
    { max: 255, message: '长度不能超过255个字符', trigger: 'blur' }
  ],
  invoice_phone: [
    { required: true, message: '请输入开票电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  contact_name: [
    { required: true, message: '请输入联系人姓名', trigger: 'blur' },
    { max: 50, message: '长度不能超过50个字符', trigger: 'blur' }
  ],
  contact_mobile: [
    { required: true, message: '请输入联系人电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
}

// 获取列表数据
const getList = async () => {
  loading.value = true
  try {
    const res = await request.get('/organization/list', {
      params: queryParams
    })
    if (res.code === 0) {
      tableData.value = res.data?.list || []
      total.value = res.data?.total || 0
    } else {
      ElMessage.error(res.msg || '获取数据失败')
    }
  } catch (error) {
    console.error('获取列表失败：', error)
    ElMessage.error('获取数据失败')
  }
  loading.value = false
}

// 搜索
const handleSearch = () => {
  queryParams.page = 1
  getList()
}

// 重置搜索
const resetQuery = () => {
  queryParams.keyword = ''
  queryParams.status = ''
  handleSearch()
}

// 新增
const handleAdd = () => {
  dialogType.value = 'add'
  dialogTitle.value = '新增企业'
  Object.keys(form).forEach(key => {
    form[key] = ''
  })
  form.invoice_type = 'normal'
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  dialogType.value = 'edit'
  dialogTitle.value = '编辑企业'
  Object.keys(form).forEach(key => {
    form[key] = row[key]
  })
  dialogVisible.value = true
}

// 获取详情
const handleDetail = async (row) => {
  try {
    const res = await request.get('/organization/detail', {
      params: { id: row.org_id }
    })
    if (res.code === 0) {
      detail.value = res.data
      detailVisible.value = true
    } else {
      ElMessage.error(res.msg || '获取详情失败')
    }
  } catch (error) {
    console.error('获取详情失败：', error)
    ElMessage.error('获取详情失败')
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const url = dialogType.value === 'add' 
          ? '/organization/create' 
          : '/organization/update'
        const res = await request.post(url, form)
        if (res.code === 0) {
          ElMessage.success(dialogType.value === 'add' ? '添加成功' : '更新成功')
          dialogVisible.value = false
          getList()
        } else {
          ElMessage.error(res.msg || '操作失败')
        }
      } catch (error) {
        console.error('提交失败：', error)
        ElMessage.error('操作失败')
      }
    }
  })
}

// 更改状态
const handleStatus = (row) => {
  const statusText = row.status ? '禁用' : '启用'
  ElMessageBox.confirm(
    `确认要${statusText}该企业吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const res = await request.post('/organization/status', {
        id: row.org_id,
        status: row.status ? 0 : 1
      })
      if (res.code === 0) {
        ElMessage.success(`${statusText}成功`)
        getList()
      } else {
        ElMessage.error(res.msg || `${statusText}失败`)
      }
    } catch (error) {
      console.error('更改状态失败：', error)
      ElMessage.error(`${statusText}失败`)
    }
  }).catch(() => {})
}

// 分页
const handleSizeChange = (val) => {
  queryParams.limit = val
  getList()
}

const handleCurrentChange = (val) => {
  queryParams.page = val
  getList()
}

onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
  
  .search-wrapper {
    margin-bottom: 20px;
  }
  
  .table-wrapper {
    margin-bottom: 20px;
  }
  
  .pagination-container {
    margin-top: 20px;
    text-align: right;
  }
}

.dialog-footer {
  text-align: right;
  padding-top: 20px;
}
</style> 